package com.flc.gateway.dataqueue;

import com.flc.gateway.config.AppConfig;
import com.flc.gateway.data.LoginData;
import com.flc.gateway.mq.MqProducer;
import com.flc.gateway.redis.RedisPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author haizi
 * @date 2018/1/2
 */
public class LoginQueue extends Thread {

    private static final Logger logger = LoggerFactory.getLogger(LoginQueue.class);

    public LoginQueue(int capacity, String topic) {
        super.setName("LoginQueue");
        this.dataQueue = new ArrayBlockingQueue<>(capacity);
        this.serverId = AppConfig.getInstance().getServerCfg().getID();
        this.jedis = RedisPool.getJedis();
    }

    @Override
    public void run() {

        logger.info("开启登录数据队列...");
        if (MqProducer.getState()) {
            logger.info("开启登录数据队列成功！");
        }
        while (MqProducer.getState()) {
            try {
                LoginData data = this.take();

                // ToDo 把取到的数据发往登陆对应的redis或者其他消息队列
                System.out.println("这是一条登陆数据");
                String key = String.valueOf(data.getDeviceId());
                jedis.hset(key, "time", String.valueOf(data.getTime()));
                jedis.hset(key, "serverId", this.serverId);
                jedis.hset(key, "imei", data.getDeviceIMEI());

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void put(LoginData data) throws InterruptedException {
        dataQueue.put(data);
    }

    private LoginData take() throws InterruptedException {
        return dataQueue.take();
    }

    private BlockingQueue<LoginData> dataQueue;
    private String serverId;
    private Jedis jedis;
}
